package com.lonewalker.sparrow.util;

import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * 事务生命周期工具
 *
 * @author Wang Yu
 * @version 4.0
 */
public class TransactionLifeCycleUtil {

    /**
     * 在事务提交后同步执行
     *
     * @param runnable 将在事务提交后执行的Runnable对象
     */
    public static void afterCommitSyncExecute(Runnable runnable) {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(
                    new TransactionSynchronizationAdapter() {
                        @Override
                        public void afterCommit() {
                            runnable.run();
                        }
                    });
        } else {
            runnable.run();
        }
    }
}
